package com.leo.core.config.spring;

import java.nio.charset.StandardCharsets;
import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 取代web.xml配置
 * 
 * @author 00fly
 * @version [版本号, 2023年4月21日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Deprecated
public class WebXmlInitializer implements WebApplicationInitializer
{
    @Override
    public void onStartup(ServletContext servletContext)
    {
        // 1、rootApplicationContext
        AnnotationConfigWebApplicationContext rootApplicationContext = new AnnotationConfigWebApplicationContext();
        rootApplicationContext.register(ApplicationConfiguration.class);
        log.info("ApplicationContextConfig注册完毕");
        // 监听root上下文的生命周期
        servletContext.addListener(new ContextLoaderListener(rootApplicationContext));
        
        // 2、CharacterEncodingFilter
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.toString());
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration filterRegistration = servletContext.addFilter("encodingFilter", characterEncodingFilter);
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        
        // 3、springmvc上下文
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(SpringMvcConfiguration.class);
        log.info("WebSpringMVCServletConfig注册完毕");
        
        // 创建并注册DispatcherServlet
        Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
        registration.setLoadOnStartup(1);// 设置启动顺序同等：
        registration.addMapping("/");
        log.info("DispatcherServlet注册完毕");
    }
}
